const fs = require('fs');
const { randomInt } = require('crypto');

// 生成包含100个随机数的数组
function generateRandomArray(length = 100, min = 0, max = 1000) {
  return Array.from({ length }, () => randomInt(min, max + 1));
}

// 插入排序算法
function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    let key = arr[i];
    let j = i - 1;

    while (j >= 0 && arr[j] > key) {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = key;
  }
  return arr;
}

// 打印数组
function printArray(arr) {
  console.log(arr.join('\n'));
}

// 将数组写入文本文件
function writeArrayToFile(arr, filename = 'sorted_numbers.txt') {
  fs.writeFileSync(filename, arr.join('\n'), 'utf8');
  console.log(`Sorted array has been written to ${filename}`);
}

// 主流程
const randomNumbers = generateRandomArray(100);
console.log('Original Array:');
printArray(randomNumbers);

const sortedNumbers = insertionSort(randomNumbers);
console.log('\nSorted Array:');
printArray(sortedNumbers);

writeArrayToFile(sortedNumbers);